#
#-*- coding: utf-8 -*-
#

from google.appengine.api import xmpp
from google.appengine.ext import db
from datetime import datetime,timedelta
import re


class At(db.Model):
	due = db.DateTimeProperty(required=True)
	user = db.StringProperty(required=True)
	desc = db.TextProperty(required=True)

def atSchedule():
	dnow = datetime.utcnow()
	query = db.GqlQuery("select * from At where due < :1",dnow)
	for item in query :
		xmpp.send_message(item.user,item.desc)
		item.delete()

def atProc(sender,cmd):
	pcmd = cmd.strip()
	pos = pcmd.find(' ')
	
	verb = pcmd
	ar = ''
	if pos != -1 :
		verb = pcmd[:pos]
		ar = pcmd[pos+1:]

	if(verb=='-list'):
		atList(sender)
	elif(verb=='-del'):
		atDel(sender,ar)
	elif(verb=='-clear'):
		atClear(sender)
	elif(verb=='-add'):
		atAdd(sender,ar)
	else:
		atHelp(sender)

def atList(sender):
	
	query = db.GqlQuery("select * from At where user = :1 order by due DESC",sender)
	result = query.fetch(1000)
	ret  = 'you have %d reminders :' % len(result)
	for item in result :
		ret += '\n [' + str( item.key().id() ) + item.due.strftime("] %Y-%m-%d %H:%M UTC ") + item.desc  
	xmpp.send_message(sender,ret)
	

def atAdd(sender,addcmd):
	# parse time
	g = addcmd.split(' ',1)
	if len(g) == 2:
		dtvalid = False
		dtnow = datetime.utcnow()
		m = re.match('(\d+):(\d+)-(\d+)-(\d+)([+-]\d+)',g[0])
		if m != None:
			delta = timedelta(hours= int(m.group(5)))
			dtnow += delta
			dt = datetime( dtnow.year,int(m.group(3)),int(m.group(4)),int(m.group(1)), int(m.group(2)) )
			dt -= delta
			dtvalid = True
		else:
			m = re.match('(\d+):(\d+)([+-]\d+)',g[0])
			if m != None:
				delta = timedelta(hours= int(m.group(3)))
				dtnow += delta
				dt = datetime( dtnow.year,dtnow.month,dtnow.day,int(m.group(1)), int(m.group(2)) )
				dt -= delta
				dtvalid = True
		if dtvalid :
			atitem = At(due =dt,user=sender,desc=g[1])
			k = atitem.put()
			xmpp.send_message(sender,'item added :)')
			return 

	atHelp(sender)

def atDel(sender,itemid):
	query = db.GqlQuery("select * from At where user = :1 ",sender)
	for item in query :
		if item.key().id() == int(itemid) :
			item.delete()
			xmpp.send_message(sender,'item deleted :)')
			return
	xmpp.send_message(sender,'item not found :(')

def atClear(sender):
	query = db.GqlQuery("select * from At where user = :1 ",sender)
	db.delete(query)
	xmpp.send_message(sender,'you have no items now')

def atHelp(sender):
	ret = ''' at has some subcmds:
		\\at or \\at -list
		\\at -del id
		\\at -add 15:36+8 take a break   # +8 your timezone 
		\\at -add 12:40-5-23+8 call Jack 
		\\at -clear
		\\at -help
			'''
	xmpp.send_message(sender,ret)
